import demoImg from "@/assets/demoImg/demo.png";
import demo1Img from "@/assets/demoImg/demo1.png";
import demo2Img from "@/assets/demoImg/demo2.png";
import {useEffect, useState, useCallback} from "react";
import {Image, Text, View, StyleSheet, TouchableOpacity, RefreshControl, ActivityIndicator} from "react-native";
import WaterfallFlow from "react-native-waterfall-flow";
import * as React from "react";
import {scaleSize} from "@/utils/screenSize";
import { LinearGradient } from "expo-linear-gradient";
import dateTimeIcon from "@/assets/images/collection/dateTime.png";
import AntDesign from '@expo/vector-icons/AntDesign';
import {router} from "expo-router";
import { format, differenceInHours } from 'date-fns';
import Empty from "@/components/empty";

const HomeActivityListComponent = function ({ list, pullLoadData, loadMoreList }) {
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [hasMore, setHasMore] = useState(true);

    const AutoHeightImage = ({ uri, fixedWidth, typeName, destName }) => {
        const [imageHeight, setImageHeight] = useState(0);

        useEffect(() => {
            // const { width, height } = Image.resolveAssetSource({ uri });
            Image.getSize(uri, (width, height) => {
                // // 计算新的高度，根据固定的宽度
                const scaleFactor = fixedWidth / width;
                const newHeight = height * scaleFactor;
                setImageHeight(newHeight);
            }, (error) => {
                console.error('Failed to load image size', error);
            });

        }, [uri, fixedWidth]);

        return (
          <View style={{ position: "relative" }}>
              <Image
                  source={{ uri }}
                  style={{
                      width: fixedWidth || 120,    // 固定宽度
                      height: imageHeight || 300,  // 动态高度
                      borderTopRightRadius: 6,
                      borderTopLeftRadius: 6,
                  }}
              />
              <View style={ styles.tagContainer }>
                  <Text style={styles.tagContainerText}>{ typeName }</Text>
              </View>
              <View style={ styles.LocationPostion }>
                  <AntDesign name="enviroment" size={10} color="white" />
                  <Text style={styles.LocationPostionText}>{ destName }</Text>
              </View>
          </View>
        );
    };
    const computedTime = function (startT, endT) {
        const year1 = format(startT, "yyyy");
        const year2 = format(endT, "yyyy");
        const day1 = format(startT, "MMdd");
        const day2 = format(endT, "MMdd");
        const time1 = format(startT, "HH:mm");
        const time2 = format(endT, "HH:mm");
        if (!startT || !endT) {
            return "";
        };

        // 计算两个时间之间的小时差
        const hoursDiff = differenceInHours(endT, startT);

        // 如果起始时间和结束时间都是 00:00，并且时间跨度是 24 小时的整数倍
        if (time1 === "00:00" && time2 === "00:00" && hoursDiff % 24 === 0) {
            if (year1 !== year2) {
                return `${format(startT, "yyyy.MM.dd")}-${format(endT, "yyyy.MM.dd")}`;
            }
            return `${format(startT, "MM.dd")}-${format(endT, "MM.dd")}`;
        }

        if (day1 === day2) {
            if (year1 !== year2) {
                return `${format(startT, "yyyy.MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "HH:mm")}`;
            }
            return `${format(startT, "MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "HH:mm")}`;
        }

        if (year1 !== year2) {
            return `${format(startT, "yyyy.MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "yyyy.MM.dd")} ${format(endT, "HH:mm")}`;
        }

        return `${format(startT, "MM.dd")} ${format(startT, "HH:mm")}-${format(endT, "MM.dd")} ${format(endT, "HH:mm")}`;
    };

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };

    const onRefresh = useCallback(() => {
        setRefreshing(true);
        pullLoadData({}, refreshing, setRefreshing);
    }, [list]);

    const loadMoreDataList = useCallback(() => {
        if (!hasMore) return;
        // console.log("加载更多")
        if (loadMoreList) {
            loadMoreList({}, loadingMore, setLoadingMore, noMore)
        };

    }, [list]);

    const noMore = function (flg) {
        setHasMore(flg)
    };

    const NoMoreData = () => {
        return (
            <View style={styles.NoMoreDatacontainer}>
                <View style={styles.NoMoreDataline} />
                <Text style={styles.NoMoreDatatext}>没有更多了</Text>
                <View style={styles.NoMoreDataline} />
            </View>
        );
    };

    const RenderItem = function ({ item }) {
        return (
           <TouchableOpacity onPress={() => goActivityDetail(item.activityId)}>
               <View style={styles.homeActivityContainer}>
                   <AutoHeightImage uri={item.coverUrl} fixedWidth={scaleSize(177)} typeName={item?.typeName} destName={item?.destName} />
                   <View style={styles.homeActivityContent}>
                       <View style={styles.homeActivityTitile}>
                           <Text numberOfLines={2} style={styles.homeActivityTitileText}>{item.title}</Text>
                       </View>
                       <View style={styles.activityDateWarp}>
                           <View style={styles.addressIcon}>
                               <Image source={dateTimeIcon} style={{ width: '100%', height: "100%" }} />
                           </View>
                           <Text style={ styles.activityDate } numberOfLines={1}>{ computedTime(item.durationStartTime, item.durationEndTime) }</Text>
                       </View>
                       <View style={styles.activityTag}>
                           {
                               item?.tags?.map((item: any, index: number) => {
                                   return (
                                       <LinearGradient
                                           // 270度渐变，右到左
                                           colors={['#FAE5CC', '#FFFFFF']}
                                           start={{ x: 0, y: 0 }} // 起点位置 (1, 0) 代表右边
                                           end={{ x: 1, y: 0 }}   // 终点位置 (0, 0) 代表左边
                                           style={{ borderRadius: 4, marginRight: 4, }}
                                           key={index}
                                       >
                                           <Text style={styles.activityTagText}>{ item }</Text>
                                       </LinearGradient>
                                   )
                               })
                           }

                       </View>
                       <View style={styles.activityBot}>
                           <Text style={styles.activityMoney}>¥{ item?.ticketsPrice }</Text>
                           {
                               item?.hasTicketsForSale == 1 && (
                                   <Text style={styles.activityBotTitle}>正在招募...</Text>
                               )
                           }
                       </View>
                   </View>
               </View>
           </TouchableOpacity>
        )
    };

    const RrenderFooter = () => {
        return (
            <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                <ActivityIndicator size="small" />
                <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
            </View>
        );
    };

    return (
        <WaterfallFlow
            data={list}
            numColumns={2}
            style={{ marginLeft: 7, }}
            renderItem={({ item }) => <RenderItem item={item} />}
            onEndReached={loadMoreDataList} // 滚动到底部触发加载更多
            onEndReachedThreshold={0.1} // 触发阈值（距离底部的比例）
            refreshControl={
                <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
            }
            ListFooterComponent={
                loadingMore ? <RrenderFooter/> : !hasMore && list.length > 4 ? (
                    <NoMoreData/>
                ) : null
            }
            ListEmptyComponent={<Empty title={"空空如也~"} />}
        />
    )
};

const styles = StyleSheet.create({
    homeActivityContainer: {
    },
    homeActivityContent: {
        paddingHorizontal: 12,
    },
    homeActivityTitile: {
        marginTop: 8,
        lineHeight: 50
    },
    homeActivityTitileText: {
        fontSize: 14,
        color: "#2A2B30",
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 6,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 3,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 3,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    activityTag: {
        flexDirection: "row",
    },
    activityTagText: {
        fontSize: 12,
        paddingLeft: 4,
        paddingTop: 3,
        paddingRight: 12,
        color: "#6E522D",
        paddingBottom: 3,
    },
    activityBot: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginBottom: 8,
        marginTop: 6,
    },
    activityMoney: {
        fontSize: 18,
        color: "#EC6138"
    },
    activityBotTitle: {
        fontSize: 12,
        color: "#333"
    },
    LocationPostion: {
        position: "absolute",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        paddingVertical: 6,
        paddingHorizontal: 4,
        bottom: 7,
        left: 9,
        backgroundColor: "rgba(0,0,0,.5)",
        borderRadius: 9,
    },
    LocationPostionText: {
        color: "#fff",
        fontSize: 10,
        marginLeft: 2,
    },
    tagContainer: {
        backgroundColor:"#EC6138",
        position: "absolute",
        top: 0,
        paddingHorizontal: 5,
        paddingVertical: 3,
        borderTopRightRadius: 20,
        borderBottomRightRadius: 20,
        borderTopLeftRadius: 6,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    tagContainerText: {
        color: "#fff",
        fontSize: 10,
    },
    footer: {
        paddingVertical: 16,
        alignItems: 'center',
    },
    NoMoreDatacontainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginVertical: 20,
        paddingBottom: 30,
    },
    NoMoreDataline: {
        width: 80,
        height: 0.5,
        backgroundColor: '#ccc',
    },
    NoMoreDatatext: {
        marginHorizontal: 10,
        color: '#888',
        fontSize: 14,
    },
});

export default HomeActivityListComponent;
